<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-calendar"></i> 商品 </el-breadcrumb-item>
                <el-breadcrumb-item>添加商品</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <el-form ref="form" :rules="rules" :model="form" label-width="100px">
                    <el-form-item label="商品名称" prop="commodityName">
                        <el-input v-model="form.commodityName"></el-input>
                    </el-form-item>

                    <el-form-item label="添加标签">
                        <el-tag
                            v-for="(tag, index) in form.tags"
                            :key="index"
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag)"
                            >{{ tag }}</el-tag
                        >
                        <el-input
                            class="input-new-tag"
                            v-if="inputVisible"
                            v-model="inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm"
                            @blur="handleInputConfirm"
                        ></el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                    </el-form-item>

                    <el-form-item label="上传图片">
                        <div class="crop-demo">
                            <img :src="cropImg" class="pre-img" />
                            <div class="crop-demo-btn">
                                选择图片
                                <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" />
                            </div>
                            <div v-show="is_error" class="error">请上传商品图片</div>
                        </div>
                        <el-dialog title="裁剪图片" :visible.sync="dialogVisible" width="35%">
                            <vue-cropper
                                ref="cropper"
                                :src="imgSrc"
                                :ready="cropImage"
                                :zoom="cropImage"
                                :cropmove="cropImage"
                                style="width: 100%; height: 400px"
                            ></vue-cropper>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="cancelCrop">取 消</el-button>
                                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
                            </span>
                        </el-dialog>
                    </el-form-item>

                    <el-form-item label="类型" prop="typeId">
                        <el-select v-model="form.typeId" placeholder="请选择">
                            <el-option
                                v-for="(item, index) in commodityType"
                                :key="index"
                                :label="item.typeName"
                                :value="item.typeId"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品属性">
                        <el-switch v-model="form.isAttribute"></el-switch>
                    </el-form-item>
                    <el-form-item label v-show="form.isAttribute">
                        <div class="drag-box">
                            <div class="drag-box-item">
                                <div class="item-title">未添加</div>
                                <draggable v-model="attributeList" @remove="removeHandle" :options="dragOptions">
                                    <transition-group tag="div" id="attributeList" class="item-ul">
                                        <div v-for="(item, index) in attributeList" class="drag-list" :key="index">{{ item.content }}</div>
                                    </transition-group>
                                </draggable>
                            </div>
                            <div class="drag-box-item">
                                <div class="item-title">已添加</div>
                                <draggable v-model="form.attributeList" @remove="removeHandle" :options="dragOptions">
                                    <transition-group tag="div" id="add_attributeList" class="item-ul">
                                        <div v-for="(item, index) in form.attributeList" class="drag-list" :key="index">
                                            {{ item.content }}
                                        </div>
                                    </transition-group>
                                </draggable>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="商品介绍" prop="desc">
                        <el-input type="textarea" rows="5" v-model="form.desc"></el-input>
                    </el-form-item>
                    <el-form-item label="商品特性1">
                        <el-input maxlength="25" show-word-limit v-model="form.characteristic1" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="商品特性2">
                        <el-input maxlength="25" show-word-limit v-model="form.characteristic2" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="商品特性3">
                        <el-input maxlength="25" show-word-limit v-model="form.characteristic3" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="商品特性4">
                        <el-input maxlength="25" show-word-limit v-model="form.characteristic4" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="price">
                        <el-input v-model="form.price"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">表单提交</el-button>
                        <el-button>取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import commodityApi from '@/api/commodity';
import VueCropper from 'vue-cropperjs';
import draggable from 'vuedraggable';
export default {
    name: 'baseform',
    data() {
        return {
            inputVisible: false,
            inputValue: '',
            commodityType: [],
            form: {
                commodityName: '',
                tags: [],
                typeId: '',
                isAttribute: false,
                attributeList: [],
                attributeIds: [],
                desc: '',
                characteristic: [],
                characteristic1: '',
                characteristic2: '',
                characteristic3: '',
                characteristic4: '',
                price: ''
            },
            is_error: false,
            rules: {
                commodityName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
                ],
                typeId: [{ required: true, message: '请选择商品类型', trigger: 'blur' }],
                desc: [
                    { required: true, message: '请输入商品介绍', trigger: 'blur' },
                    { min: 20, max: 200, message: '长度在 20 到 200 个字符', trigger: 'blur' }
                ],
                price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }]
            },
            defaultSrc: '',
            // defaultSrc: require('@/assets/img/img.jpg'),
            imgSrc: '',
            cropImg: '',
            dialogVisible: false,
            dragOptions: {
                animation: 120,
                scroll: true,
                group: 'sortlist',
                ghostClass: 'ghost-style'
            },
            attributeList: [
                // {
                //     id: 1,
                //     content: '开发图表组件'
                // }
            ]
        };
    },
    components: {
        VueCropper,
        draggable
    },
    created() {
        this.cropImg = this.defaultSrc;
        this.getAllAttributes();
        this.getAllCommodityTypes();
    },
    methods: {
        getAllCommodityTypes() {
            commodityApi.getAllCommodityTypes().then((response) => {
                var data = response.data.data;
                this.commodityType = data;
                console.log(this.commodityType);
            });
        },
        getAllAttributes() {
            commodityApi.getAllAttributes().then((response) => {
                console.log(response.data);
                var data = response.data.data;
                var currentId = 0;
                var currentValue = '';
                var addObject;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].attributeId != currentId) {
                        if (i != 0) {
                            addObject = { id: data[i - 1].attributeId, content: data[i - 1].attributeName + ':' + currentValue };
                            console.log(addObject);
                            this.attributeList.push(addObject);
                            currentValue = '';
                        }
                        currentId = data[i].attributeId;
                        console.log(data[i].attributeId, ':', data[i].attributeName);
                        currentValue += data[i].value;
                    } else {
                        currentValue += '/' + data[i].value;
                        console.log(currentValue);
                    }
                }
                addObject = { id: data[data.length - 1].attributeId, content: data[data.length - 1].attributeName + ':' + currentValue };
                this.attributeList.push(addObject);
            });
        },
        removeHandle(event) {
            console.log(event);
            this.$message.success(`从 ${event.from.id} 移动到 ${event.to.id} `);
        },
        dataURLtoFile(dataurl, filename) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename + '.jpg', { type: mime });
        },
        onSubmit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.cropImg != '') {
                        this.is_error = false;
                        // console.log('base64', this.cropImg);
                        // console.log('file', this.dataURLtoFile(this.cropImg, this.form.commodityName));
                        let formData = new FormData();
                        for (var i = 0; i < this.form.attributeList.length; i++) {
                            this.form.attributeIds.push(this.form.attributeList[i].id);
                        }
                        this.form.attributeIds = JSON.stringify(this.form.attributeIds);
                        this.form.characteristic.push(this.form.characteristic1);
                        this.form.characteristic.push(this.form.characteristic2);
                        this.form.characteristic.push(this.form.characteristic3);
                        this.form.characteristic.push(this.form.characteristic4);
                        this.form.characteristic = JSON.stringify(this.form.characteristic);
                        this.form.tags = JSON.stringify(this.form.tags);
                        formData.append('formData', JSON.stringify(this.form));
                        formData.append('file', this.dataURLtoFile(this.cropImg, this.form.commodityName));
                        commodityApi.addCommodity(formData).then((response) => {
                            this.$message.success('提交成功！');
                            this.form.characteristic = [];
                            this.form.tags = [];
                        });
                    } else {
                        this.is_error = true;
                    }
                } else {
                    if (this.cropImg != '') {
                        this.is_error = false;
                    } else {
                        this.is_error = true;
                    }
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        setImage(e) {
            const file = e.target.files[0];
            if (!file.type.includes('image/')) {
                return;
            }
            const reader = new FileReader();
            reader.onload = (event) => {
                this.dialogVisible = true;
                this.imgSrc = event.target.result;
                this.$refs.cropper && this.$refs.cropper.replace(event.target.result);
            };
            reader.readAsDataURL(file);
            this.is_error = false;
        },
        cropImage() {
            this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
            console.log('cropImage', this.cropImg);
        },
        cancelCrop() {
            this.dialogVisible = false;
            this.cropImg = this.defaultSrc;
        },
        // tag
        handleClose(tag) {
            this.form.tags.splice(this.form.tags.indexOf(tag), 1);
        },

        showInput() {
            this.inputVisible = true;
            this.$nextTick((_) => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.form.tags.push(inputValue);
            }
            this.inputVisible = false;
            this.inputValue = '';
        }
    }
};
</script>

<style scoped>
.pre-img {
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
}
.crop-demo {
    display: flex;
    align-items: flex-end;
}
.crop-demo-btn {
    position: relative;
    width: 100px;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    margin-left: 30px;
    background-color: #409eff;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    box-sizing: border-box;
}
.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}
/* drag */
.drag-box {
    display: flex;
    user-select: none;
}
.drag-box-item {
    flex: 1;
    max-width: 330px;
    min-width: 300px;
    background-color: #eff1f5;
    margin-right: 16px;
    border-radius: 6px;
    border: 1px #e1e4e8 solid;
}
.item-title {
    padding: 8px 8px 8px 12px;
    font-size: 14px;
    line-height: 1.5;
    color: #24292e;
    font-weight: 600;
}
.item-ul {
    padding: 0 8px 8px;
    height: 500px;
    overflow-y: scroll;
}
.item-ul::-webkit-scrollbar {
    width: 0;
}
.drag-list {
    border: 1px #e1e4e8 solid;
    padding: 10px;
    margin: 5px 0 10px;
    list-style: none;
    background-color: #fff;
    border-radius: 6px;
    cursor: pointer;
    -webkit-transition: border 0.3s ease-in;
    transition: border 0.3s ease-in;
}
.drag-list:hover {
    border: 1px solid #20a0ff;
}
.drag-title {
    font-weight: 400;
    line-height: 25px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}
.ghost-style {
    display: block;
    color: transparent;
    border-style: dashed;
}
/* tag */
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
.error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    margin-left: 20px;
}
</style>

